<?php

function getAPL($leagueId) {
	$sql = "select p.id, p.team, p.firstName, p.surname, p.playerType from player p where p.id not in (select tp.playerId from teamplayer tp";
	$sql .= " inner join team t on tp.teamId = t.id where t.leagueId = $leagueId and traded = false) and firstName <> 'Penalty' order by surname, firstName";
	
	$result = mysql_query($sql);
	
	$array = array();
	while($row = mysql_fetch_array($result)) {
		$draftItem = new Player();
		$draftItem->id = $row['id'];
		$draftItem->playerFirstName = $row['firstName'];
		$draftItem->playerSurname = $row['surname'];
		$draftItem->team = $row['team'];
		$draftItem->playerType = $row['playerType'];
		
		$array[] = $draftItem;
	}
	
	usort($array, "compare");
	
	
	return $array;
}

function getAllPlayers() {
	$sql = "select p.id, p.team, p.firstName, p.surname, p.playerType from player p order by surname, firstName";
	
	$result = mysql_query($sql);
	
	$array = array();
	while($row = mysql_fetch_array($result)) {
		$draftItem = new Player();
		$draftItem->id = $row['id'];
		$draftItem->playerFirstName = $row['firstName'];
		$draftItem->playerSurname = $row['surname'];
		$draftItem->team = $row['team'];
		$draftItem->playerType = $row['playerType'];
		
		$array[] = $draftItem;
	}
	
	usort($array, "compare");
	
	
	return $array;
}

function deletePlayers($selectedPlayers) {
	$playerIds = "";
	$count = count($selectedPlayers);
	for ($i = 0; $i < $count; $i++) {
		if ($i > 0) {
			$playerIds .= ",";
		}
		$playerIds .= $selectedPlayers[$i];
	}
	
	$sql = "DELETE FROM player where id in (" . $playerIds . ");";
	mysql_query($sql);
	
}

function addPlayers($selectedPlayers, $team) {
	$playerIds = "";
	$count = count($selectedPlayers);
	for ($i = 0; $i < $count; $i++) {
		$player = $selectedPlayers[$i];
		$firstName = trim(substr($player, 0, strpos($player, " ")));
		$surname = trim(substr($player, strpos($player, " ")));
		$sql = "INSERT INTO player (firstName, surname, team) values ('$firstName', '$surname', '$team');";
		mysql_query($sql);
	}
	
}

function addPlayer($firstName, $surname, $twam, $playerType) {
	$sql = "INSERT INTO player (firstName, surname, team, playerType) values ('$firstName', '$surname', '$team', ";
	if ($playerType != null) {
		$sql .= "'$playerType');";
	}
	else {
		$sql .= "null";
	}
	$sql .= ");";
	
	mysql_query($sql);
	
}

function getPlayerID($firstName, $surname, $team) {
	$sql = "SELECT id FROM player where firstName = '" . $firstName . "' AND surname = '" . str_replace("'", "''", $surname) . "' AND team = '" . $team . "'";
	$result = mysql_query($sql);
	
	$row = mysql_fetch_array($result);
	$id = $row['id'];
	
	
	return $id;
}
?>